package com.quickcode.example.atomic;

import com.quickcode.annotation.Safe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 可以用于保证一段代码永远只会执行一次
 * Created by 张波 on 2019/10/22.
 */
@Slf4j
@Safe
public class ExampleAtomic6 {

    public static final int clientTotal = 5000;

    public static final int threadTotal = 200;

    public static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0 ; i < clientTotal ; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception:{}",e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            log.info("开始进入线程等待");
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("exception:{}",e);
        }
        executorService.shutdown();
        log.error("最终结果atomicBoolean：{}",atomicBoolean.get());
    }

    private static void add() {
        if(atomicBoolean.compareAndSet(false,true)) {
            log.info("执行了方法");
        }
    }
}
